//
//  ZMyOrderCarVC.m
//  DistributorAB
//
//  Created by LZY on 2019/10/10.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "ZMyOrderCarVC.h"

#import "ZMyOrderCarStoreCell.h"//店铺cell
#import "ZMyOrderCarShopOrderCell.h"//产品cell
#import "ZMyOrderCarBottomView.h"//底部view
#import "ZMyOrderCarOrderModel.h"

#import "BBuyNowShopStoreVC.h"//店铺
#import "BBuyNowShopDetailVC.h"//配件产品详情
#import "ZSubmitMyOrderVC.h"//提交预订单

@interface ZMyOrderCarVC () <UITableViewDelegate,UITableViewDataSource,ZMyOrderCarStoreCellDelegate,ZMyOrderCarShopOrderCellDelegate,ZMyOrderCarBottomViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *orderArray;
@property (nonatomic, strong) ZMyOrderCarBottomView *viewBottom;
@end

@implementation ZMyOrderCarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"预订车";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    [self.rightbutton setTitle:@"管理" forState:(UIControlStateNormal)];
    
    _orderArray = [NSMutableArray array];
    
    [self setupViewAction];
    
    [MBProgressHUD showHUDAddedTo:self.view msg:@"数据加载中" animated:YES];
    [self requestData];
    
    //通知监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestData) name:USER_ADD_ORDER_SUCCESS object:nil];
}
#pragma mark - 界面布局
- (void)setupViewAction{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight, kScreen_Width, kScreen_Height - kNaviHeight - TabbarSafeBottomMargin - 56) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    KKTableViewNoDataView *viewPlaceHolder = [[KKTableViewNoDataView alloc] initWithFrame:CGRectMake((kScreen_Width - 100) / 2.0, (kScreen_Height - 72) / 2.0, 100, 72) image:imgname(@"tableviewPlaseholder") viewClick:^{}];
    _tableView.placeHolderView = viewPlaceHolder;
    
    [_tableView registerClass:[ZMyOrderCarStoreCell class] forCellReuseIdentifier:NSStringFromClass([ZMyOrderCarStoreCell class])];
    [_tableView registerClass:[ZMyOrderCarShopOrderCell class] forCellReuseIdentifier:NSStringFromClass([ZMyOrderCarShopOrderCell class])];
    
    _viewBottom = [[ZMyOrderCarBottomView alloc] initWithFrame:CGRectMake(0, kScreen_Height - 56 - TabbarSafeBottomMargin, kScreen_Width, 56 + TabbarSafeBottomMargin)];
    _viewBottom.delegate = self;
    _viewBottom.hidden = YES;
    [self.view addSubview:_viewBottom];
}
#pragma mark - 数据请求
- (void)requestData{
    kWeakSelf;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObjectIfNotNil:@"1" forKey:@"user_type"];
    
    [NetWorkTool POST:myOrderCar param:dict success:^(id dic) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [weakSelf.orderArray removeAllObjects];
        NSArray *orderList = [dic objectForKeyNotNil:@"data"];
        [orderList enumerateObjectsUsingBlock:^(NSDictionary  * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ZMyOrderCarOrderModel *model = [ZMyOrderCarOrderModel mj_objectWithKeyValues:obj];
            [weakSelf.orderArray addObjectNotNil:model];
        }];
        [weakSelf.tableView reloadData];
        weakSelf.viewBottom.hidden = NO;
        weakSelf.viewBottom.btnSelect.selected = NO;
        KMyLog(@"预订车有没有数据 %@", dic);
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        ShowToastWithText(@"数据请求失败");
    } needUser:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.orderArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ZMyOrderCarOrderModel *model = [self.orderArray objectAtIndexSafe:section];
    return model.parts.count + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZMyOrderCarOrderModel *model = [self.orderArray objectAtIndexSafe:indexPath.section];
    if (indexPath.row == 0) {
        ZMyOrderCarStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZMyOrderCarStoreCell class]) forIndexPath:indexPath];
        cell.model = model;
        cell.delegate = self;
        cell.indexPath = indexPath;
        return cell;
    }else{
        BShopPartModel *partModel = [model.parts objectAtIndexSafe:indexPath.row - 1];
        ZMyOrderCarShopOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZMyOrderCarShopOrderCell class]) forIndexPath:indexPath];
        cell.partModel = partModel;
        cell.indexPath = indexPath;
        if (indexPath.row == model.parts.count) {
            cell.isRoundBg = YES;
        }else{
            cell.isRoundBg = NO;
        }
        cell.delegate = self;
        return cell;
    }
    return [UITableViewCell new];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZMyOrderCarOrderModel *model = [self.orderArray objectAtIndexSafe:indexPath.section];
    if (indexPath.row == 0) {
        //进入店铺
//        BBuyNowShopStoreVC *vc = [BBuyNowShopStoreVC new];
//        vc.storeID = model.Id;
//        vc.orderModel = model;
//        [self.navigationController pushViewController:vc animated:YES];
    }else{
        //进入产品详情
        BBuyNowShopDetailVC *vc = [BBuyNowShopDetailVC new];
        BShopPartModel *partModel = [model.parts objectAtIndexSafe:indexPath.row - 1];
        vc.shopID = partModel.partsId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return [ZMyOrderCarStoreCell cellHeight];
    }else{
        return [ZMyOrderCarShopOrderCell cellHeight];
    }
}
#pragma mark - ZMyOrderCarStoreCellDelegate
- (void)orderCarStoreCellClick:(NSIndexPath *)indexPath isSelected:(BOOL)isSelected{
    //刷新section
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:indexPath.section];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    
    [self checkIsAllSelected];
    
}
#pragma mark - ZMyOrderCarShopOrderCellDelegate
//选中按钮点击
- (void)orderCarShopOrderCellClick:(NSIndexPath *)indexPath isSelected:(BOOL)isSelected{
    //刷新cell
    NSIndexPath *index = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
    NSIndexPath *indexZero = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
    
    ZMyOrderCarOrderModel *model = [self.orderArray objectAtIndexSafe:indexPath.section];
    __block NSInteger selectedNumber = 0;
    [model.parts enumerateObjectsUsingBlock:^(BShopPartModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isOrderSelected == YES) {
            selectedNumber++;
        }
    }];
    if (selectedNumber == model.parts.count) {
        //全选
        model.isSelected = YES;
    }else{
        //非全选
        model.isSelected = NO;
    }
    
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index,indexZero,nil] withRowAnimation:UITableViewRowAnimationNone];
    
    [self checkIsAllSelected];
}
//检查是否触发了全选
- (void)checkIsAllSelected{
    __block NSInteger selectedSection = 0;
    [self.orderArray enumerateObjectsUsingBlock:^(ZMyOrderCarOrderModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            selectedSection++;
        }
    }];
    if (selectedSection == self.orderArray.count) {
        //全选
        _viewBottom.btnSelect.selected = YES;
    }else{
        _viewBottom.btnSelect.selected = NO;
    }
}
#pragma mark - ZMyOrderCarBottomViewDelegate
- (void)orderCarBottomViewClick:(ZMyOrderCarBottomViewClickType)clickType{
    if (clickType == ZMyOrderCarBottomViewClickTypeNoneSelected) {
        //取消全选
        [self.orderArray enumerateObjectsUsingBlock:^(ZMyOrderCarOrderModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelected = NO;
            [obj.parts enumerateObjectsUsingBlock:^(BShopPartModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.isOrderSelected = NO;
            }];
        }];
        [self.tableView reloadData];
    }else if (clickType == ZMyOrderCarBottomViewClickTypeSelected){
        //全选
        [self.orderArray enumerateObjectsUsingBlock:^(ZMyOrderCarOrderModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelected = YES;
            [obj.parts enumerateObjectsUsingBlock:^(BShopPartModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.isOrderSelected = YES;
            }];
        }];
        [self.tableView reloadData];
    }else if (clickType == ZMyOrderCarBottomViewClickTypeBuy){
        //我要预订
        [self managerOrderCarRequestDataWithType:1];
    }else if (clickType == ZMyOrderCarBottomViewClickTypeDelete){
        //删除
        [self managerOrderCarRequestDataWithType:2];
    }
}
#pragma mark - 交互事件
//管理
- (void)rightClick{
    if (self.viewBottom.btnType == ZMyOrderCarBottomViewClickTypeBuy) {
        [self.viewBottom updateBtnBuy:ZMyOrderCarBottomViewClickTypeDelete];
        [self.rightbutton setTitle:@"完成" forState:(UIControlStateNormal)];
    }else if (self.viewBottom.btnType == ZMyOrderCarBottomViewClickTypeDelete){
        [self.viewBottom updateBtnBuy:ZMyOrderCarBottomViewClickTypeBuy];
        [self.rightbutton setTitle:@"管理" forState:(UIControlStateNormal)];
    }
}
#pragma mark - 管理预订车接口处理
- (void)managerOrderCarRequestDataWithType:(NSInteger)type{
    __block NSString *orderIDStr = @"";//订单ID拼接
    __block NSString *countStr = @"";//订单数量拼接
    
    [self.orderArray enumerateObjectsUsingBlock:^(ZMyOrderCarOrderModel  * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.parts enumerateObjectsUsingBlock:^(BShopPartModel * _Nonnull objPart, NSUInteger idx, BOOL * _Nonnull stop) {
            if (objPart.isOrderSelected) {
                orderIDStr = [orderIDStr stringByAppendingString: orderIDStr.length > 0 ? [NSString stringWithFormat:@",%@",objPart.Id] : objPart.Id];
                countStr = [countStr stringByAppendingString: countStr.length > 0 ? [NSString stringWithFormat:@",%@",objPart.count] : objPart.count];
            }
        }];
    }];
    
    if (orderIDStr.length > 0) {
        kWeakSelf;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObjectIfNotNil:@(type) forKey:@"type"];
        [dict setObjectIfNotNil:@"1" forKey:@"user_type"];
        [dict setObjectIfNotNil:orderIDStr forKey:@"ids"];
        [dict setObjectIfNotNil:countStr forKey:@"counts"];
        [NetWorkTool POST:managerMyOrderCar param:dict success:^(id dic) {
            if (type == 1) {
                //提交成功
                NSArray *orderList = [dic objectForKeyNotNil:@"data"];
                __block NSMutableArray *submitOrderArray = [NSMutableArray array];
                [orderList enumerateObjectsUsingBlock:^(NSDictionary  * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    ZMyOrderCarOrderModel *model = [ZMyOrderCarOrderModel mj_objectWithKeyValues:obj];
                    [submitOrderArray addObjectNotNil:model];
                }];
                ZSubmitMyOrderVC *vc = [ZSubmitMyOrderVC new];
                vc.submitOrderArray = submitOrderArray;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } else if (type == 2){
                //删除成功
                [weakSelf requestData];
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } other:^(id dic) {
            ShowToastWithText(dic[@"msg"]);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } fail:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } needUser:YES];
    } else {
        ShowToastWithText(@"请选择预订的产品");
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
